<template>
    <div class="home">
        <h1>2048</h1>
        <div class="author">Directed by __proto__</div>
        <div v-if="!username" class="login-form">
            <input 
                v-model="inputUsername" 
                placeholder="请输入用户名" 
                @keyup.enter="handleLogin"
            >
            <button @click="handleLogin">登录</button>
        </div>
        <div v-else class="menu">
            <div class="user-info">
                <h2>欢迎, {{ username }}!</h2>
            </div>
            <div v-if="showSaveSelect" class="save-select">
                <h3>选择存档</h3>
                <div class="saves-list">
                    <div 
                        v-for="save in saves" 
                        :key="save.id" 
                        class="save-item"
                    >
                        <div class="save-content" @click="loadSave(save)">
                            <div class="save-info">
                                <span class="score">得分: {{ save.current_score }}</span>
                                <span>保存时间: {{ new Date(save.saved_at).toLocaleString() }}</span>
                            </div>
                        </div>
                        <button class="delete-btn" @click="confirmDelete(save)">×</button>
                    </div>
                </div>
                <button @click="() => showSaveSelect = false">返回</button>
            </div>
            <div v-else class="buttons">
                <button @click="startNewGame">新游戏</button>
                <button v-if="hasSaves" @click="handleLoadGame">加载游戏</button>
                <button @click="viewLeaderboard">查看排行榜</button>
                <button @click="handleLogout">退出登录</button>
            </div>
        </div>

        <!-- 确认删除对话框 -->
        <div v-if="showDeleteConfirm" class="confirm-dialog">
            <div class="confirm-content">
                <p>确定要删除这个存档吗？</p>
                <div class="confirm-buttons">
                    <button @click="handleDelete">确定</button>
                    <button @click="cancelDelete">取消</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { login, getSaves, hideSave } from '../api'

export default {
    name: 'Home',
    setup() {
        const router = useRouter()
        const username = ref(localStorage.getItem('username') || '')
        const inputUsername = ref('')
        const saves = ref([])
        const hasSaves = ref(false)
        const showSaveSelect = ref(false)
        const showDeleteConfirm = ref(false)
        const selectedSave = ref(null)

        const loadSaves = async () => {
            if (!username.value) return
            try {
                const { data } = await getSaves(username.value)
                saves.value = data.saves || []
                hasSaves.value = saves.value.length > 0
            } catch (error) {
                console.error('获取存档失败:', error)
            }
        }

        const handleLogin = async () => {
            if (!inputUsername.value) return
            try {
                await login(inputUsername.value)
                username.value = inputUsername.value
                localStorage.setItem('username', inputUsername.value)
                await loadSaves()
            } catch (error) {
                console.error('登录失败:', error)
            }
        }

        const handleLogout = () => {
            localStorage.removeItem('username')
            localStorage.removeItem('currentSave')
            username.value = ''
            inputUsername.value = ''
            saves.value = []
            hasSaves.value = false
            showSaveSelect.value = false
        }

        const confirmDelete = (save) => {
            selectedSave.value = save
            showDeleteConfirm.value = true
        }

        const handleDelete = async () => {
            if (!selectedSave.value) return
            try {
                await hideSave(selectedSave.value.id)
                await loadSaves()
                showDeleteConfirm.value = false
                selectedSave.value = null
                if (saves.value.length === 0) {
                    showSaveSelect.value = false
                }
            } catch (error) {
                console.error('删除存档失败:', error)
            }
        }

        const cancelDelete = () => {
            showDeleteConfirm.value = false
            selectedSave.value = null
        }

        const startNewGame = () => {
            localStorage.removeItem('currentSave')
            router.push('/game')
        }

        const handleLoadGame = async () => {
            await loadSaves()
            if (saves.value.length === 1) {
                // 只有一个存档时直接加载
                loadSave(saves.value[0])
            } else if (saves.value.length > 1) {
                // 多个存档时显示选择界面
                showSaveSelect.value = true
            }
        }

        const loadSave = (save) => {
            // 将选中的存档信息存储到 localStorage，包括完整的游戏状态
            localStorage.setItem('currentSave', JSON.stringify({
                id: save.id,
                username: save.username,
                game_state: save.game_state,
                current_score: save.current_score,
                saved_at: save.saved_at
            }))
            router.push('/game')
        }

        const viewLeaderboard = () => {
            router.push('/leaderboard')
        }

        const goHome = () => {
            router.push('/')
        }

        onMounted(async () => {
            if (username.value) {
                await loadSaves()
            }
            // 添加路由变化监听
            router.beforeEach(async (to, from, next) => {
                if (to.path === '/' && username.value) {
                    await loadSaves()
                }
                next()
            })
        })

        return {
            username,
            inputUsername,
            saves,
            hasSaves,
            showSaveSelect,
            showDeleteConfirm,
            handleLogin,
            handleLogout,
            startNewGame,
            handleLoadGame,
            loadSave,
            viewLeaderboard,
            confirmDelete,
            handleDelete,
            cancelDelete,
            goHome
        }
    }
}
</script>

<style scoped>
.home {
    text-align: center;
    padding: 20px;
    overflow: hidden;
    height: 100vh;
}

.author{
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
    transform: translate(0px,-20px);
}

h1 {
    font-size: 48px;
    color: #776e65;
    margin-bottom: 30px;
}

.login-form {
    margin: 20px 0;
}

input {
    padding: 10px;
    font-size: 16px;
    margin-right: 10px;
    border: 2px solid #bbada0;
    border-radius: 6px;
}

button {
    padding: 10px 20px;
    font-size: 16px;
    background-color: #8f7a66;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    margin: 10px;
}

button:hover {
    background-color: #776e65;
}

.menu {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;
}

.buttons {
    display: flex;
    flex-direction: column;
    gap: 10px;
    width: 200px;
}

.save-select {
    background: #bbada0;
    padding: 20px;
    border-radius: 6px;
    width: 80%;
    max-width: 400px;
}

.saves-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin: 20px 0;
    max-height: 60vh;
    overflow-y: auto;
}

.save-item {
    display: flex;
    align-items: center;
    gap: 10px;
    background: #eee4da;
    padding: 15px;
    border-radius: 6px;
    transition: background-color 0.2s;
}

.save-item:hover {
    background: #ede0c8;
}

.save-content {
    flex-grow: 1;
    cursor: pointer;
    background: transparent;
}

.delete-btn {
    padding: 5px 10px;
    font-size: 18px;
    background-color: #f65e3b;
    min-width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.save-info {
    display: flex;
    flex-direction: column;
    gap: 5px;
    color: #776e65;
}

.save-info span {
    font-size: 14px;
}

.save-info .score {
    font-size: 14px;
    font-weight: 600;
}

h3 {
    color: white;
    margin: 0;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 20px;
}

.logout-btn {
    padding: 5px 10px;
    font-size: 14px;
    background-color: #bbada0;
}

.confirm-dialog {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.confirm-content {
    background: white;
    padding: 20px;
    border-radius: 6px;
    text-align: center;
}

.confirm-buttons {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin-top: 20px;
}

.confirm-buttons button {
    min-width: 80px;
}

.game-container {
    margin: 40px auto;
    padding: 30px;
}
</style> 